from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
import enum
from apps import db
import shortuuid


class GenderEnUm(enum.Enum):
    male = 1
    female = 2
    secret = 3
    unknown = 4


class FrontUser(db.Model):
    __tablename__ = 'front_user'
    id = db.Column(db.String(100), default=shortuuid.uuid, primary_key=True)
    username = db.Column(db.String(20), nullable=True, unique=True)
    _password = db.Column(db.String(120), nullable=True)
    email = db.Column(db.String(20), nullable=True, unique=True)
    telephone = db.Column(db.String(11), unique=True)
    avatar = db.Column(db.String(150), nullable=True, default='/static/images/default_avatar.png')
    real_name = db.Column(db.String(50), nullable=True)
    signature = db.Column(db.String(200), default='这个人很懒，什么也没留下.')  # 签名
    gender = db.Column(db.Enum(GenderEnUm), default=GenderEnUm.unknown)  # 枚举性别
    add_time = db.Column(db.DateTime, default=datetime.now)

    def __init__(self, *args, **kwargs):
        if 'password' in kwargs:
            self.password = kwargs.get('password')
            kwargs.pop('password')
        super(FrontUser, self).__init__(*args, **kwargs)

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, raw_password):
        self._password = generate_password_hash(raw_password)

    def check_password(self, raw_password):
        return check_password_hash(self.password, raw_password)


class FrontComment(db.Model):
    __talbename__ = 'front_comment'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.String(200), nullable=False)
    article_id = db.Column(db.Integer, db.ForeignKey('cms_article.id'))
    author_id = db.Column(db.String(100), db.ForeignKey('front_user.id'))
    add_time = db.Column(db.DateTime, default=datetime.now)

    article = db.relationship('CMSArticle', backref='front_comments')
    author = db.relationship('FrontUser', backref='front_comments')
